<template>
  <el-drawer
    size="600"
    v-model="dialogVisibled"
    :before-close="handleClose"
    :title="dialogTitle"
    :close-on-click-modal="false"
    @open="handleDialogOpen"
  >
    <el-divider />
    <div style="margin: 10px">
      <el-form ref="ruleFormRef" :model="flowNodeData" :rules="rules" label-width="auto">
        <el-divider>设置节点信息</el-divider>
        <br />
        <el-form-item label="节点id：" prop="NodeId">
          <el-input
            v-model="flowNodeData.NodeId"
            placeholder="请输入节点id"
            maxlength="20"
            disabled="true"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="节点名称：" prop="NodeName">
          <el-input
            v-model="flowNodeData.NodeName"
            placeholder="请输入节点名称"
            maxlength="10"
            show-word-limit
            clearable
          />
        </el-form-item>
        <div
          v-if="
            flowNodeData.NodeType !== FlowNodeTypeEnum.input &&
            flowNodeData.NodeType !== FlowNodeTypeEnum.output
          "
        >
          <el-form-item label="审核人：" prop="ReviewerIds">
            <draggable
              v-model="flowNodeData.ReviewerIds"
              style="display: contents"
              handle=".drag-handle"
            >
              <template #item="{ element, index }">
                <div style="width: 100%; display: flex; align-items: center">
                  <el-tree-select
                    class="ReviewerSelectStyle"
                    v-model="flowNodeData.ReviewerIds[index]"
                    :key="element"
                    :data="userList"
                    :props="defaultProps"
                    check-strictly
                    :default-expand-all="true"
                    :render-after-expand="false"
                    placeholder="请选择审核人"
                    :style="{
                      width:
                        flowNodeData.NodeType === FlowNodeTypeEnum.countersign
                          ? '80%'
                          : '100%',
                    }"
                  >
                  </el-tree-select>

                  <div v-if="flowNodeData.NodeType === FlowNodeTypeEnum.countersign">
                    <el-icon
                      class="drag-handle"
                      size="20"
                      title="拖动排序"
                      style="cursor: pointer; margin-left: 5px"
                      ><Rank
                    /></el-icon>
                    <el-icon
                      color="green"
                      title="添加审核人"
                      size="20"
                      style="cursor: pointer; margin-left: 5px"
                      @click="addReviewerIdClick(index)"
                      ><Plus
                    /></el-icon>
                    <el-icon
                      v-if="index !== 0"
                      color="red"
                      size="20"
                      title="删除审核人"
                      style="cursor: pointer; margin-left: 5px"
                      @click="delReviewerIdClick(index)"
                      ><Minus
                    /></el-icon>
                  </div>
                </div>
              </template>
            </draggable>
          </el-form-item>
          <el-form-item label="抄送给：">
            <el-tree-select
              v-model="flowNodeData.CarbonCopyUser"
              :data="userList"
              check-strictly
              multiple
              multiple-limit="10"
              :default-expand-all="true"
              :render-after-expand="false"
              placeholder="请选择抄送人，最多选10位抄送人"
              style="width: 95%"
            >
            </el-tree-select>
            <el-tooltip
              content="当前节点审核通过后，流程会自动发送给抄送人"
              effect="customized"
            >
              <el-icon size="22" color="#F56C6C"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
          <div v-if="flowNodeData.NodeType === FlowNodeTypeEnum.countersign">
            <el-divider>会签方式</el-divider>
            <br />
            <el-form-item label="会签方式：">
              <el-radio-group v-model="flowNodeData.CountersignWay">
                <el-radio :value="NodeCountersignWayEnum.AllReviewerExamine"
                  >所有人审批（且签）
                </el-radio>
                <el-radio :value="NodeCountersignWayEnum.EitherReviewerExamine"
                  >任意一人审批（或签）
                </el-radio>
                <el-tooltip effect="customized">
                  <template #content>
                    且签：该节点审核人都会审批<br />
                    或签：该节点审核人，任意一人审批即可
                  </template>
                  <el-icon size="22" color="#F56C6C"><QuestionFilled /></el-icon>
                </el-tooltip>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="会签顺序："
              v-if="
                flowNodeData.CountersignWay === NodeCountersignWayEnum.AllReviewerExamine
              "
            >
              <el-radio-group v-model="flowNodeData.CountersignOrder">
                <el-radio :value="NodeCountersignOrderEnum.OrderAsc"
                  >按审核人顺序审批
                </el-radio>
                <el-radio :value="NodeCountersignOrderEnum.NoOrder"
                  >不按顺序审批
                </el-radio>
                <el-tooltip effect="customized">
                  <template #content>
                    按顺序审批：上一个审核人审批后，下一个审核人才能审批<br />
                    不按顺序审批：审批没有先后顺序<br />
                    说明：【或签】该属性无作用
                  </template>
                  <el-icon size="22" color="#F56C6C"><QuestionFilled /></el-icon>
                </el-tooltip>
              </el-radio-group>
            </el-form-item>
          </div>
          <el-divider>设置表单字段权限</el-divider>
          <br />
          <div
            style="text-align: left; display: flex; align-items: center; font-size: 12px"
          >
            <el-icon size="16" color="#F56C6C"><QuestionFilled /></el-icon
            >设置隐藏后，审核人员不能查看隐藏字段（表单中的字段）
          </div>
          <el-table
            :data="flowNodeData.FormFieldAuth"
            size="small"
            style="width: 100%; overflow-y: scroll"
            max-height="300"
          >
            <el-table-column prop="label" />
            <el-table-column width="140">
              <template #default="{ row }">
                <el-radio-group v-model="row.disabled">
                  <el-radio :value="false" size="small">显示</el-radio>
                  <el-radio :value="true" size="small">隐藏</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
          </el-table>
          <br />
          <el-divider>设置审核期限</el-divider>
          <br />
          <el-form-item label="审核期限：">
            <el-radio-group v-model="flowNodeData.IsSetExamineExpire">
              <el-radio :value="true">设置审核期限</el-radio>
              <el-radio :value="false">任意时间审核</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="超时日期："
            v-if="flowNodeData.IsSetExamineExpire"
            prop="ExpireDate"
          >
            <!-- <el-date-picker
              :disabled-date="disabledBeforeToday"
              v-model="flowNodeData.ExpireDate"
              format="YYYY-MM-DD hh:mm"
              value-format="YYYY-MM-DD hh:mm"
              type="datetime"
              :show-now="false"
              style="width: 100%"
              placeholder="请选择超时日期，不能选择当天及之前的日期"
            /> -->
            从
            <el-input-number
              v-model="flowNodeData.ExpireDate"
              :min="1"
              :max="100"
              style="width: 120px"
            />
            <el-select v-model.number="flowNodeData.ExpireType" style="width: 80px">
              <el-option label="天" :value="1" />
              <el-option label="小时" :value="2" />
            </el-select>
            后，未审批自动执行超时动作
          </el-form-item>
          <el-form-item label="超时动作：" v-if="flowNodeData.IsSetExamineExpire">
            <el-radio-group v-model="flowNodeData.ExpireAction">
              <el-radio :value="ExpireActionEnum.NoAction">等待审批</el-radio>
              <el-radio :value="ExpireActionEnum.Approve">自动批准</el-radio>
              <el-radio :value="ExpireActionEnum.AuditRefuse">自动拒绝</el-radio>
              <el-radio :value="ExpireActionEnum.RejectNode">驳回到上个节点</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="过期提醒："
            v-if="flowNodeData.IsSetExamineExpire"
            prop="IsExpireRemind"
          >
            <el-radio-group v-model="flowNodeData.IsExpireRemind">
              <el-radio :value="true">提醒</el-radio>
              <el-radio :value="false">不提醒</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="提前："
            v-if="flowNodeData.IsExpireRemind && flowNodeData.IsSetExamineExpire"
          >
            <el-input-number
              v-model="flowNodeData.SoonExpireDate"
              :min="10"
              :max="60"
              style="width: 65%"
            >
              <template #suffix>
                <el-icon><Timer /></el-icon>
              </template>
            </el-input-number>
            <span>分钟提醒审核人</span>
          </el-form-item>
          <el-form-item
            label="提示信息："
            prop="RemindContent"
            v-if="flowNodeData.IsExpireRemind && flowNodeData.IsSetExamineExpire"
          >
            <el-input
              v-model="flowNodeData.RemindContent"
              placeholder="请输入提示信息，即将超时会把该内容发送给审核人"
              maxlength="20"
              style="width: 100%"
              show-word-limit
              clearable
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <el-button icon="Close" size="large" type="danger" plain @click="handleClose"
        >取消</el-button
      >
      <el-button
        type="primary"
        size="large"
        icon="Check"
        plain
        @click="submitForm(ruleFormRef)"
        >保存节点</el-button
      >
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { getDepartmentTree, getUserByCorporationKey } from "@/api/overallAuthApi";
import {
  ExpireActionEnum,
  FlowNodeTypeEnum,
  NodeCountersignOrderEnum,
  NodeCountersignWayEnum,
} from "@/enum/flowEnum";
import { CorporationKey } from "@/model/const";
import { flowNodeModel } from "@/model/flow/flowModel";
import { selectOutPut } from "@/model/public/selectModel";
import { treeOutPut } from "@/model/public/treeModel";
import { dayjs, ElMessage, FormInstance, FormRules } from "element-plus";
import { cloneDeep } from "lodash";
import { computed, PropType, reactive, ref } from "vue";
import draggable from "vuedraggable";
const props = defineProps({
  isVisibles: Boolean,
  dialogTitle: String,
  nodeModel: { type: Object as PropType<flowNodeModel>, required: true },
  nodeType: { type: Number, required: true },
});
const emit = defineEmits(["closeBnt", "saveNodeClick"]);
//用户数据
const userList = ref<selectOutPut[]>([]);

//流程节点模型
const flowNodeData = ref<flowNodeModel>({
  Id: "",
  NodeId: "",
  NodeName: "",
  NodeType: props.nodeType,
  ReviewerIds: [],
  CarbonCopyUser: [],
  FormFieldAuth: [],
  IsSetExamineExpire: false,
  ExpireDate: 1,
  ExpireAction: ExpireActionEnum.NoAction,
  IsExpireRemind: false,
  SoonExpireDate: 10,
  RemindContent: "",
  CountersignWay: NodeCountersignWayEnum.AllReviewerExamine,
  CountersignOrder: NodeCountersignOrderEnum.OrderAsc,
  ExpireType: 1,
});
//部门数据
const departmentList = ref<treeOutPut[]>([]);
//打开时加载
const handleDialogOpen = function () {
  getCorporationDepartmentListMsg();
  getUserList();
  const nodeData = cloneDeep(props.nodeModel);
  flowNodeData.value.NodeId = nodeData.NodeId;
  flowNodeData.value.NodeName = nodeData.NodeName;
  flowNodeData.value.ReviewerIds =
    nodeData.ReviewerIds === undefined ? [""] : nodeData.ReviewerIds;
  flowNodeData.value.CarbonCopyUser = nodeData.CarbonCopyUser;
  flowNodeData.value.FormFieldAuth = nodeData.FormFieldAuth;
  flowNodeData.value.IsSetExamineExpire = nodeData.IsSetExamineExpire;
  flowNodeData.value.ExpireDate = nodeData.ExpireDate;
  flowNodeData.value.ExpireAction = nodeData.ExpireAction;
  flowNodeData.value.IsExpireRemind = nodeData.IsExpireRemind;
  flowNodeData.value.SoonExpireDate = nodeData.SoonExpireDate;
  flowNodeData.value.RemindContent = nodeData.RemindContent;
  flowNodeData.value.NodeType = props.nodeType;
  flowNodeData.value.CountersignWay = nodeData.CountersignWay;
  flowNodeData.value.CountersignOrder = nodeData.CountersignOrder;
  flowNodeData.value.ExpireType =
    nodeData.ExpireType === 0 || nodeData.ExpireType === undefined
      ? 1
      : nodeData.ExpireType;
  // resetForm(ruleFormRef.value);
};

//tree指定操作
const defaultProps = {
  //设置属于下级角色的菜单，不能勾选
  disabled(data: selectOutPut) {
    var model = flowNodeData.value.ReviewerIds.find((s) => s == data.value);
    if (model != undefined || model != null) {
      return true;
    }
  },
};
//获取部门数据
const getCorporationDepartmentListMsg = function () {
  getDepartmentTree().then(({ data, code, msg }) => {
    if (code == 200) {
      departmentList.value = data;
    } else {
      ElMessage.warning(msg);
    }
  });
};

//获取用户
const getUserList = function () {
  getUserByCorporationKey({
    corporationKey: CorporationKey,
  }).then(({ data, code }) => {
    if (code == 200) {
      userList.value = data;
    }
  });
};

//设置日期限制
const disabledBeforeToday = function (time: any) {
  return time.getTime() < Date.now();
};

//#region  验证规则

//注册验证
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<typeof flowNodeData.value>>({
  NodeId: [
    {
      required: true,
      message: "节点id不能为空!",
      trigger: "blur",
    },
  ],
  NodeName: [
    {
      required: true,
      message: "节点名称不能为空!",
      trigger: "blur",
    },
  ],
  ReviewerIds: [
    {
      required: true,
      message: "审核人员不能为空!",
      trigger: "change",
    },
  ],
  ExpireDate: [
    {
      required: true,
      message: "超时日期不能为空!",
      trigger: "change",
    },
  ],
  RemindContent: [
    {
      required: true,
      message: "提示信息不能为空!",
      trigger: "blur",
    },
  ],
});
//清除验证
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

//#endregion

//添加审核人事件
const addReviewerIdClick = function (index: number) {
  if (flowNodeData.value.ReviewerIds.length > 10) {
    ElMessage.warning("会签节点最多添加审核人");
  } else {
    flowNodeData.value.ReviewerIds.splice(index + 1, 0, "");
  }
};

//删除审核人事件
const delReviewerIdClick = function (index: number) {
  flowNodeData.value.ReviewerIds.splice(index, 1);
};

//保存节点信息
const submitForm = function (formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (
        flowNodeData.value.ReviewerIds.some((f) => f === "" || f === undefined) &&
        flowNodeData.value.NodeType !== FlowNodeTypeEnum.input &&
        flowNodeData.value.NodeType !== FlowNodeTypeEnum.output
      ) {
        ElMessage.warning("审核人不能为空");
        return;
      }
      if (
        flowNodeData.value.CarbonCopyUser !== undefined &&
        flowNodeData.value.CarbonCopyUser.some((f) =>
          flowNodeData.value.ReviewerIds.includes(f)
        )
      ) {
        ElMessage.warning("审核人和抄送人不能是同一个人");
      } else {
        flowNodeData.value.ExpireDate =
          flowNodeData.value.ExpireDate === 0 ||
          flowNodeData.value.ExpireDate === undefined
            ? 1
            : flowNodeData.value.ExpireDate;
        flowNodeData.value.ReviewerIds =
          flowNodeData.value.ReviewerIds === undefined
            ? []
            : flowNodeData.value.ReviewerIds;

        emit("saveNodeClick", cloneDeep(flowNodeData.value));
        handleClose();
      }
    }
  });
};

//是否显示dialog
const dialogVisibled = computed(() => {
  return props.isVisibles;
});
//关闭事件
const handleClose = () => {
  emit("closeBnt");
  resetForm(ruleFormRef.value);
};
</script>

<style lang="css">
.ReviewerSelectStyle {
  margin-bottom: 5px;
}
</style>
